package com.itheima.tlias84.servrce.impl;


import com.alibaba.fastjson2.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.tlias84.annotaion.ReportLog;
import com.itheima.tlias84.dto.SelectEmpDTO;
import com.itheima.tlias84.dto.SelectEmpDetailDTO;
import com.itheima.tlias84.entity.Expr;
import com.itheima.tlias84.mapper.EmpMapper;
import com.itheima.tlias84.mapper.ExprMapper;
import com.itheima.tlias84.po.InsertEmpParam;
import com.itheima.tlias84.po.SelectEmpPageParam;
import com.itheima.tlias84.po.updateEmpParam;
import com.itheima.tlias84.servrce.EmpService;
import com.itheima.tlias84.utils.ResultUtil;
import com.itheima.tlias84.vo.pageVO;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Service
@Slf4j
public class EmpServiceImpl implements EmpService {
    @Resource
    EmpMapper empMapper;

    @Resource
    ExprMapper exprMapper;


    @Override
    public ResultUtil selectEmpByPage(SelectEmpPageParam param) {
        //计算分页
        // param.setPage((param.getPage()-1)*param.getPageSize());
        //注意 pagehelper 会自动统计一个count sql,并且会自动拼接limet
        //因此必须写在自己的sql之前
        Page<Object> page = PageHelper.startPage(param.getPage(), param.getPageSize());
        List<SelectEmpDTO> dto = empMapper.selectEmpByPage(param);
        pageVO<SelectEmpDTO> pageVO = new pageVO<>();
        pageVO.setTotal(page.getTotal());
        pageVO.setRows(dto);

        return ResultUtil.success(pageVO);
    }

    @Transactional(rollbackFor = Exception.class) //2.加上这个注解自动开启事务,提交事务并且回滚事务 rollbackFor = Exception.class自定义异常
    @Override
    public int deleteEmpById(List<Integer> ids) {
//        int a=1;
//        if(a==1){
//            throw new RuntimeException("删除出现异常");
//        }
        //先删除员工
        int i = empMapper.delectEmpById(ids);
        int i1 = exprMapper.batchDeleteExpr(ids);
        log.info("删除员工:{},删除工作履历:{}",i,i1);
        return i;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int insertEmp(InsertEmpParam param) {
        //获取当前时间
        param.setCreateTime(LocalDateTime.now());
        param.setUpdateTime(LocalDateTime.now());
        int flag = empMapper.insertEmp(param);
        //插入工作履历
        log.info("员工回显的主键id:{}",param.getId());
        List<Expr> exprList = param.getExprList();

        //if (Objects.nonNull(param.getExprList()) && !param.getExprList().isEmpty()) {
        //CollectionUtils 工具类中的isNotEmpty 可以判空还可以判断是不是null
        if(CollectionUtils.isNotEmpty(exprList)){
            //赋值员工id 以及时间
            exprList = exprList.stream().map(t -> {
                t.setEmpId(param.getId());
                t.setCreateTime(LocalDateTime.now());
                t.setUpdateTime(LocalDateTime.now());
                return t;
            }).toList();
            int i = exprMapper.batchInsertExpr(exprList);
            log.info("插入员工履历:{}",i);
        }

        return flag;
    }
    @ReportLog
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int updateEmp(updateEmpParam param) {
        param.setUpdateTime(LocalDateTime.now());
        //先更新员工表信息
        int empRows = empMapper.updateEmp(param);
        //再删除该员工所有履历
        int exprDelRows = exprMapper.batchDeleteExpr(List.of(param.getId()));
        log.info("删除{}条旧履历",exprDelRows);
        //新增所有履历
        List<Expr> exprList = param.getExprList();
        if(CollectionUtils.isNotEmpty(exprList)){
            //赋值员工id 以及时间
            exprList = exprList.stream().map(t -> {
                t.setEmpId(param.getId());
                t.setCreateTime(LocalDateTime.now());
                t.setUpdateTime(LocalDateTime.now());
                return t;
            }).toList();
            int i = exprMapper.batchInsertExpr(exprList);
        //    log.info("插入{}条新员工履历:{}",i);
        }
        return empRows;
    }

    @Override
    public List<SelectEmpDTO> selectEmpList() {
        List<SelectEmpDTO> selectEmpDTOS = empMapper.selectEmpList();
        return selectEmpDTOS;
    }


    @Override
    public SelectEmpDetailDTO selectEmpById(Integer id) {
        //先查询员工
        SelectEmpDetailDTO dto = empMapper.selectEmpById(id);
        //再查询工作履历
        List<Expr> exprs = exprMapper.selectExprByEmpId(id);
        dto.setExprList(exprs);
        return dto;
    }

    @Override
    public ResultUtil empJobData() {
        List<Integer> jobs = empMapper.empJobData();
        Map<String, List<Integer>> map = jobs.stream().collect(Collectors.groupingBy(t -> {
            return switch (t) {
                case 1 -> "班主任";
                case 2 -> "讲师";
                case 3 -> "学工主管";
                case 4 -> "教研主管";
                case 5 -> "咨询师";
                default -> "其他";
            };
        }));
        Set<String> jobList = map.keySet();
        List<Integer> dataList = map.values().stream().map(List::size).toList();
//        HashMap<String, Object> resultMap = new HashMap<>();
//        resultMap.put("jobList",jobList);
//        resultMap.put("dataList",dataList);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("jobList",jobList);
        jsonObject.put("dataList",dataList);
        return ResultUtil.success(jsonObject);
    }
}
